package dfl.bysj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dfl.bysj.config.RedisKey;
import dfl.bysj.entity.Academy;
import dfl.bysj.entity.UpdateBind;
import dfl.bysj.mapper.AcademyMapper;
import dfl.bysj.mapper.UpdateBindMapper;
import dfl.bysj.service.AcademyService;
import dfl.bysj.service.UpdateBindService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author DFL
 * @since 2022-04-26
 */
@Slf4j
@Service
@NoArgsConstructor
public class UpdateBindServiceImpl extends ServiceImpl<UpdateBindMapper, UpdateBind> implements UpdateBindService {

    private RedisTemplate redisTemplate;

    private UpdateBindMapper updateBindMapper;

    private List<UpdateBind> updateBinds;

    @Autowired
    public void setUpdateBindMapper(UpdateBindMapper updateBindMapper) {
        this.updateBindMapper = updateBindMapper;
    }

    private AtomicReference<UpdateBind> updateBindAtomicReference= new AtomicReference<>(new UpdateBind());



    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }






    private void getUpdateBinds(){
        updateBinds= (List<UpdateBind>) redisTemplate.opsForValue().get(RedisKey.ALL_UPDATEBIND);
        if (updateBinds==null){
            updateRedisOfUpdateBinds();
        }
    }

    private void updateRedisOfUpdateBinds(){
        updateBinds=list();
        redisTemplate.opsForValue().set(RedisKey.ALL_UPDATEBIND,updateBinds);
    }

    public int insertUpdateBind(UpdateBind updateBind){
        int res=updateBindMapper.insert(updateBind);

        updateRedisOfUpdateBinds();
        return res;
    }

    @Override
    public List<UpdateBind> getAllUpdateBind() {
        getUpdateBinds();
        return updateBinds;
    }

    @Override
    public void deleteUpdateBindByUseId(Integer use_id) {
        updateBindMapper.delete(new QueryWrapper<UpdateBind>().eq("use_id", use_id));
        updateRedisOfUpdateBinds();
    }

    @Override
    public UpdateBind getUpdateBindByUseId(Integer use_id) {
        getUpdateBinds();
        updateBinds.stream()
                .filter(s-> Objects.equals(s.getUseId(), use_id))
                .forEach(s-> updateBindAtomicReference.set(s));

        if (updateBindAtomicReference.get().getId()==null){
            return null;
        }
        return updateBindAtomicReference.get();
    }

}
